import { useRequest } from 'ahooks'
import { Divider, Empty, Input, Typography } from 'antd'
import React, { useState } from 'react'
import request from 'umi-request'
import { TaskType } from '../settings'
import { DATASOURCE_ID_HEADER } from '../LogPage'
import ValidationTaskContent from './ValidationTaskContent'
import HttpCallTaskContent from './HttpCallTaskContent'
import TransformTaskContent from './TransformTaskContent'
import CustomTaskContent from './CustomTaskContent'
import InvocationTaskContent from './InvocationTaskContent'
import PageLoading from '@/components/PageLoading'

const { Text } = Typography
const { TextArea } = Input

function renderError(stackTrace) {
  if (stackTrace) {
    return (
      <>
        <Divider />
        <div className="ant-detail-title">任务异常信息</div>
        <Text copyable={{ text: stackTrace }}>异常堆栈信息</Text>
        <TextArea
          className="margin-top"
          value={stackTrace}
          autoSize={{ minRows: 30, maxRows: 30 }}
        />
      </>
    )
  }
  return null
}

function TaskContent({ taskLog, datasourceId }) {
  const { taskLogId, taskType, shardingKey } = taskLog

  const [dataMap, setDataMap] = useState({})

  const { loading } = useRequest(
    () => {
      if (dataMap[taskLogId])
        return Promise.resolve(dataMap[taskLogId])

      return request.get(
        `/processLog/getTaskLogContent?taskLogId=${taskLogId}&shardingKey=${shardingKey || ''}`,
        {
          headers: {
            [DATASOURCE_ID_HEADER]: datasourceId,
          },
        },
      )
    },
    {
      onSuccess(data) {
        setDataMap({
          ...dataMap,
          [taskLogId]: data,
        })
      },
      refreshDeps: [taskLogId],
    },
  )

  const taskLogContent = dataMap[taskLogId]

  if (loading)
    return <PageLoading />

  if (!taskLogContent)
    return <Empty />

  const content = JSON.parse(taskLogContent.content)

  let detailContent
  if (taskType === TaskType.VALIDATION)
    detailContent = <ValidationTaskContent content={content} />
  else if (taskType === TaskType.HTTP_CALL)
    detailContent = <HttpCallTaskContent content={content} />
  else if (taskType === TaskType.TRANSFORM)
    detailContent = <TransformTaskContent content={content} />
  else if (taskType === TaskType.CUSTOM)
    detailContent = <CustomTaskContent content={content} />
  else if (taskType === TaskType.INVOCATION)
    detailContent = <InvocationTaskContent content={content} />

  if (detailContent) {
    return (
      <>
        {detailContent}
        {renderError(taskLogContent.stackTrace)}
      </>
    )
  }

  return <Empty />
}

export default TaskContent
